package stack.be.touch.ui;

import greendroid.app.GDActivity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


import net.sf.stackwrap4j.stackauth.StackAuth;
import net.sf.stackwrap4j.stackauth.entities.Site;

import stack.be.touch.R;
import stack.be.touch.adapter.SitesPickerAdapter;
import stack.be.touch.dao.SiteDAO;
import stack.be.touch.dto.SiteDTO;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

public class PickSitesActivity extends GDActivity {
	
	private SiteDAO mSiteDAO;
	private Cursor sitesCursor;
	ListView listView;
	private List<Site> sites;
	private ArrayList<SiteDTO> mSites = new ArrayList<SiteDTO>();
	
	private ArrayList<SiteDTO> mSitesSelected = new ArrayList<SiteDTO>();
	
	private SitesPickerAdapter mAdapter;
	private EditText mFilter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setActionBarContentView(R.layout.pick_sites);
		
		getActionBar().setTitle("Pick Sites");
		
		mSiteDAO = new SiteDAO(PickSitesActivity.this);
		sitesCursor = mSiteDAO.getMySites(SiteDTO.TABLE_NAME);
        startManagingCursor(sitesCursor);
        sitesCursor.moveToFirst();
        
        // populate data to array list
        if(sitesCursor.getCount() > 0) {
//	        int i = 0;
	        while(!sitesCursor.isAfterLast()){
	        	if (mSiteDAO.getChecked(sitesCursor) == 1){
		        	SiteDTO site = new SiteDTO(mSiteDAO.getName(sitesCursor), mSiteDAO.getEndpoint(sitesCursor),mSiteDAO.getPosition(sitesCursor), 1);
//		        	mSitesSelected.add(i,site);
		        	mSitesSelected.add(site);
	        	}
//	        	i++;
	        	sitesCursor.moveToNext();
	        }
        }
        
        sites = new ArrayList<Site>();
        listView = (ListView)findViewById(R.id.listSites);
		mAdapter = new SitesPickerAdapter(PickSitesActivity.this, R.layout.row_checked, mSites);
//		mAdapter = new SitesPickerAdapter(PickSitesActivity.this, R.layout.row_checked, mSitesSelected);
		
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View item, int position,
					long id) {
				mSites.get(position).toggleChecked();
				mAdapter.notifyDataSetChanged();
				
			}
		});
		listView.setAdapter(mAdapter);
		
		new getSites().execute();
		
	}
	
	private class getSites extends AsyncTask<Void, Void, List<Site>>{
		private Exception e;

		@Override
		protected List<Site> doInBackground(Void... params) {
			
			try {
				return StackAuth.getAllSites();
			} catch (Exception e) {
				this.e = e;
					sitesCursor.moveToFirst();
			        while(!sitesCursor.isAfterLast()){
				        SiteDTO site = new SiteDTO(mSiteDAO.getName(sitesCursor), mSiteDAO.getEndpoint(sitesCursor),mSiteDAO.getPosition(sitesCursor), mSiteDAO.getChecked(sitesCursor));
				        mSites.add(site);
			        	sitesCursor.moveToNext();
			        }
				return null;
			}
			
		}

		@Override
		protected void onPostExecute(List<Site> result) {
			if (isFinishing()) return;
			if (e != null) {
				if (sitesCursor.getCount() <= 0) {
					new AlertDialog.Builder(PickSitesActivity.this)
						.setTitle("Error")
						.setMessage("Require Internet Connection for first time RUNNING")
						.setCancelable(false)
						.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						}).create().show();
				}
//				Log.e(Const.TAG, "Failed to get sites", e);
//				}else{
////					int i = 0;
//					sitesCursor.moveToFirst();
//			        while(!sitesCursor.isAfterLast()){
//				        MySite site = new MySite(mSiteDAO.getName(sitesCursor), mSiteDAO.getEndpoint(sitesCursor),mSiteDAO.getPosition(sitesCursor), mSiteDAO.getChecked(sitesCursor));
////				        mSites.add(i,site);
//				        mSites.add(site);
////				        i++;
//			        	sitesCursor.moveToNext();
//			        }
//				}
				
			}
			else {
				sites.clear();
				sites.addAll(result);
//				mSites = mSitesSelected;
				int i = 0;
				boolean isDup = false;
//				for (Site s: sites) {
//					MySite mysite = new MySite(s.getName(), s.getApiEndpoint(), i, 0);
//					mSites.add(i, mysite);
//					i++;
//				}
				// POSITION OF SITE IN DB IS POS IN LIST
				for (SiteDTO siteSelected: mSitesSelected) {
//					mSites.set(siteSelected.getPosition(), siteSelected);
					mSites.add(siteSelected);
				}
				
				for (Site s: sites) {
					for(SiteDTO site: mSitesSelected) {
						if((site.getName().equals(s.getName()))) {
							isDup = true;
						}else{
							isDup = false;
						}
					}
					
					if(!isDup) {
					SiteDTO mysite = new SiteDTO(s.getName(), s.getApiEndpoint(), i, 0);
	//				mSites.add(i, mysite);
					mSites.add(mysite);
					i++;
					}
				
				}
				
				
			}
			
			
			updateListView();
		
		}

		
	
	}
	protected void updateListView() {
//		mSitesFiltered.clear();
//		mSitesFiltered.addAll(mSites);
		mAdapter.notifyDataSetChanged();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			mSiteDAO.removeAll(SiteDTO.TABLE_NAME);
			for(SiteDTO site : mSites) {
//				if(site.isChecked() == 1) 
//				mSiteDAO.removeSite(site);
				mSiteDAO.addSite(site);
			}
//			Intent sitesAct = new Intent();
			setResult(RESULT_OK);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	
}// CLASS
